package com.pets.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pets.entity.*;
import com.pets.mapper.*;
import com.pets.service.IFileInformationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pets.utils.Result;
import com.pets.viewModels.FileViewModels;
import com.pets.viewModels.StatisticsViewModels;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.modelmapper.ModelMapper;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 * 文件信息 服务实现类
 * </p>
 *
 * @author 啦啦啦
 * @since 2024-04-09
 */
@Service
public class FileInformationServiceImpl extends ServiceImpl<FileInformationMapper, FileInformation> implements IFileInformationService {

    //文件
    @Autowired
    private FileInformationMapper fileInformationMapper;

    //打分
    @Autowired
    private ScoringMapper scoringMapper;

    //下载记录
    @Autowired
    private DownloadRecordMapper downloadRecordMapper;

    //用户
    @Autowired
    private UsersMapper usersMapper;

    //收藏
    @Autowired
    private CollectMapper collectMapper;

    //语言类型
    @Autowired
    private LanguageTypeMapper languageTypeMapper;

    /**
     * 创建文件
     */
    @Override
    public Result register(FileInformation fileInformation) {
        fileInformation.setCreateTime(LocalDateTime.now());
        if(fileInformation.getLanguageTypeId()==null){
            Result.fail("未设置语言类型！");
        }
        fileInformation.setNumberOfTimes(0);//获赞次数
        fileInformation.setIsAdopt(false);//默认没有被采纳
        Users users = usersMapper.selectById(fileInformation.getUserId());
        if(users==null){
            Result.fail("未查询到创建用户信息！");
        }
        Integer integral = users.getIntegral();
        integral++;
        users.setIntegral(integral);
        if(fileInformationMapper.insert(fileInformation)>0){
            if(usersMapper.updateById(users)>0){
                return Result.success("创建成功！");
            }else {
                return Result.fail("添加积分失败，联系管理员手动添加，或者联系开发者！");
            }
        }else {
            return Result.fail("创建失败！");
        }
    }

    /**
     * 删除文件
     */
    @Override
    public Result deleteById(Integer id) {
        /*FileInformation fileInformation = fileInformationMapper.selectById(id);
        if(!user.getIsAdministrators()&&!fileInformation.getUserId().equals(user.getUserId())){
            return Result.fail("不能删除他人文件！");
        }*/
        return fileInformationMapper.deleteById(id)>0?Result.success("删除成功！"):Result.fail("删除失败！");
    }

    /**
     * 修改文件信息
     */
    @Override
    public Result updateData(FileInformation fileInformation) {
        return fileInformationMapper.updateById(fileInformation)>0?Result.success("修改成功！"):Result.fail("修改失败！");
    }

    /**
     * 分页查询
     */
    @Override
    public Result selectPage(Integer page, Integer pageSize, String fileName, Integer languageTypeId, Integer developmentTool, Integer projectTypesOf, Boolean isOpen, Integer userId) {
        //返回模型
        List<FileViewModels> fileViewModelsList = new ArrayList<>();
        //查询文件
        LambdaQueryWrapper<FileInformation> lqw = new LambdaQueryWrapper<>();
        lqw.like(fileName != null && !fileName.isEmpty(), FileInformation::getFileName, fileName)
                .eq(languageTypeId != null, FileInformation::getLanguageTypeId, languageTypeId)
                .eq(developmentTool != null, FileInformation::getDevelopmentTool, developmentTool)
                .eq(projectTypesOf != null, FileInformation::getProjectTypesOf, projectTypesOf)
                .eq(isOpen != null, FileInformation::getIsOpen, isOpen)
                .eq(userId != null, FileInformation::getUserId, userId);
        IPage<FileInformation> Page = new Page<>(page, pageSize);
        IPage<FileInformation> IPage = fileInformationMapper.selectPage(Page, lqw);
        //新返回模型
        IPage<FileViewModels> newIPage = new Page<>();
        newIPage.setPages(IPage.getPages());
        newIPage.setCurrent(IPage.getCurrent());
        newIPage.setSize(IPage.getSize());
        newIPage.setTotal(IPage.getTotal());
        List<FileInformation> fileInformationList = IPage.getRecords();
        if(fileInformationList==null||fileInformationList.size()<=0){
            return Result.success("查询成功！",newIPage);
        }
        //获取文件id集合
        List<Integer> fileIds = fileInformationList.stream().map(FileInformation::getFileId).filter(Objects::nonNull).distinct().collect(Collectors.toList()); // 收集结果
        //查询分数
        LambdaQueryWrapper<Scoring> scoringQuery = new LambdaQueryWrapper<>();
        scoringQuery.in(Scoring::getFileId,fileIds);
        List<Scoring> scoringList = scoringMapper.selectList(scoringQuery);
        //查询收藏次数
        LambdaQueryWrapper<Collect> collectQuery = new LambdaQueryWrapper<>();
        collectQuery.in(!fileIds.isEmpty(),Collect::getFileId,fileIds);
        List<Collect> collectList = collectMapper.selectList(collectQuery);
        //查询下载次数
        LambdaQueryWrapper<DownloadRecord> downloadRecordQuery = new LambdaQueryWrapper<>();
        downloadRecordQuery.in(!fileIds.isEmpty(),DownloadRecord::getFileId,fileIds);
        List<DownloadRecord> downloadRecordList = downloadRecordMapper.selectList(downloadRecordQuery);
        //对象映射器
        ModelMapper modelMapper = new ModelMapper();
        for (FileInformation fileInformation : fileInformationList) {
            FileViewModels fileViewModel = modelMapper.map(fileInformation, FileViewModels.class);
            // 查询文件分数
            List<Scoring> scoringTmp = scoringList.stream()
                    .filter(a -> a.getFileId().equals(fileInformation.getFileId())) // 使用equals比较对象
                    .collect(Collectors.toList()); // 收集匹配的元素到列表中
            if (scoringTmp.size()>0){
                System.out.println("有打分");
                HashMap<String,Double> tmp = new HashMap<>();
                for (Scoring scoring : scoringTmp) {
                    tmp.put(usersMapper.selectById(scoring.getUserId()).getNickname(),scoring.getFraction());
                }
                fileViewModel.setDownloadRecordMap(tmp);
            }else {
                System.out.println("没有打分");
                fileViewModel.setDownloadRecordMap(new HashMap<>());
            }
            //查询文件收藏次数
            if (collectList!=null &&collectList.size()>0){
                long collectCount = collectList.stream()
                        .filter(a -> a.getFileId().equals(fileInformation.getFileId()))
                        .count();
                fileViewModel.setCollectCount(Math.toIntExact(collectCount));
            }
            //查询文件下载次数
            if (downloadRecordList!=null &&downloadRecordList.size()>0){
                long downloadRecordCount = downloadRecordList.stream()
                        .filter(a -> a.getFileId().equals(fileInformation.getFileId()))
                        .count();
                fileViewModel.setDownloadRecordCount(Math.toIntExact(downloadRecordCount));
            }
            //文件属于语言类型
            if(fileViewModel.getLanguageTypeId()!=null){
                LanguageType languageType = languageTypeMapper.selectById(fileViewModel.getLanguageTypeId());
                if(languageType!=null){
                    fileViewModel.setLanguageTypeName(languageType.getLanguageTypeName());
                }
            }else {
                fileViewModel.setLanguageTypeName("未知");
            }
            //添加返回集合
            fileViewModelsList.add(fileViewModel);
        }
        // 使用Stream API和sorted方法进行降序排序
        List<FileViewModels> sortedEntities = fileViewModelsList.stream()
                .sorted(Comparator.comparing(FileViewModels::getCreateTime).reversed())
                .collect(Collectors.toList());
        newIPage.setRecords(sortedEntities);
        return Result.success("查询成功", newIPage);
    }

    /**
     * 统计数据
     */
    @Override
    public Result orderStatistics(LocalDate beginTime, LocalDate endTime) {
        //返回模型
        List<StatisticsViewModels> statisticsViewModelsList = new ArrayList<>();
        if (beginTime==null||endTime==null){
            return Result.fail("开始时间与结束时间不能为空！");
        }
        // 确保开始日期不晚于结束日期
        if (beginTime.isAfter(endTime)) {
            return Result.fail("开始日期不能晚于结束日期！");
        }
        //查询下载次数
        LambdaQueryWrapper<DownloadRecord> downloadRecordQuery = new LambdaQueryWrapper<>();
        downloadRecordQuery.ge(DownloadRecord::getCreateTime, beginTime.atStartOfDay())
                .lt(DownloadRecord::getCreateTime, endTime .plusDays(1).atStartOfDay());
        List<DownloadRecord> downloadRecordList = downloadRecordMapper.selectList(downloadRecordQuery);
        //查询上传次数
        LambdaQueryWrapper<FileInformation> fileInformationQuery = new LambdaQueryWrapper<>();
        fileInformationQuery.ge(FileInformation::getCreateTime, beginTime.atStartOfDay())
                .lt(FileInformation::getCreateTime, endTime .plusDays(1).atStartOfDay());
        List<FileInformation> fileInformationList = fileInformationMapper.selectList(fileInformationQuery);
        // 计算两个日期之间的天数差（包括两个日期本身）
        long daysBetween = ChronoUnit.DAYS.between(beginTime, endTime) + 1;
        // 使用IntStream生成包含所有日期的列表
        List<LocalDate> datesBetween = IntStream.rangeClosed(0, (int) (daysBetween - 1))
                .mapToObj(beginTime::plusDays)
                .collect(Collectors.toList());
        for (LocalDate localDate : datesBetween) {
            StatisticsViewModels statisticsViewModels = new StatisticsViewModels();
            statisticsViewModels.setTime(localDate.toString());//时间
            //查询当天下载记录
            if (downloadRecordList != null && downloadRecordList.size() > 0) {
                List<DownloadRecord> collect = downloadRecordList.stream()
                        .filter(a -> {
                            LocalDate entityDate = a.getCreateTime().toLocalDate();
                            return entityDate.equals(localDate);
                        }).collect(Collectors.toList());
                //没有订单
                if (collect.size() > 0)
                    statisticsViewModels.setDownloadRecordCount(collect.size());
            }
            //查询当天上传记录
            if (fileInformationList != null && fileInformationList.size() > 0) {
                List<FileInformation> collect = fileInformationList.stream()
                        .filter(a -> {
                            LocalDate entityDate = a.getCreateTime().toLocalDate();
                            return entityDate.equals(localDate);
                        }).collect(Collectors.toList());
                //没有订单
                if (collect.size() > 0)
                    statisticsViewModels.setUploadCount(collect.size());
            }
            statisticsViewModelsList.add(statisticsViewModels);
        }
        return Result.success("成功",statisticsViewModelsList);
    }

    @Override
    public Result bountyPage(Integer page, Integer pageSize, Integer bountyListId, Integer userId) {
        //返回模型
        List<FileViewModels> fileViewModelsList = new ArrayList<>();
        //查询文件
        LambdaQueryWrapper<FileInformation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(bountyListId != null, FileInformation::getBountyListId, bountyListId);
        IPage<FileInformation> Page = new Page<>(page, pageSize);
        IPage<FileInformation> IPage = fileInformationMapper.selectPage(Page, lqw);
        //新返回模型
        IPage<FileViewModels> newIPage = new Page<>();
        newIPage.setPages(IPage.getPages());
        newIPage.setCurrent(IPage.getCurrent());
        newIPage.setSize(IPage.getSize());
        newIPage.setTotal(IPage.getTotal());
        List<FileInformation> fileInformationList = IPage.getRecords();
        if(fileInformationList==null||fileInformationList.size()<=0){
            return Result.success("查询成功！",newIPage);
        }
        //获取文件id集合
        List<Integer> fileIds = fileInformationList.stream().map(FileInformation::getFileId).filter(Objects::nonNull).distinct().collect(Collectors.toList()); // 收集结果
        //查询分数
        LambdaQueryWrapper<Scoring> scoringQuery = new LambdaQueryWrapper<>();
        scoringQuery.in(Scoring::getFileId,fileIds);
        List<Scoring> scoringList = scoringMapper.selectList(scoringQuery);
        //查询收藏次数
        LambdaQueryWrapper<Collect> collectQuery = new LambdaQueryWrapper<>();
        collectQuery.in(!fileIds.isEmpty(),Collect::getFileId,fileIds);
        List<Collect> collectList = collectMapper.selectList(collectQuery);
        //查询下载次数
        LambdaQueryWrapper<DownloadRecord> downloadRecordQuery = new LambdaQueryWrapper<>();
        downloadRecordQuery.in(!fileIds.isEmpty(),DownloadRecord::getFileId,fileIds);
        List<DownloadRecord> downloadRecordList = downloadRecordMapper.selectList(downloadRecordQuery);
        //对象映射器
        ModelMapper modelMapper = new ModelMapper();
        for (FileInformation fileInformation : fileInformationList) {
            FileViewModels fileViewModel = modelMapper.map(fileInformation, FileViewModels.class);
            // 查询文件分数
            List<Scoring> scoringTmp = scoringList.stream()
                    .filter(a -> a.getFileId().equals(fileInformation.getFileId())) // 使用equals比较对象
                    .collect(Collectors.toList()); // 收集匹配的元素到列表中
            if (scoringTmp.size()>0){
                System.out.println("有打分");
                HashMap<String,Double> tmp = new HashMap<>();
                for (Scoring scoring : scoringTmp) {
                    tmp.put(usersMapper.selectById(scoring.getUserId()).getNickname(),scoring.getFraction());
                }
                fileViewModel.setDownloadRecordMap(tmp);
            }else {
                System.out.println("没有打分");
                fileViewModel.setDownloadRecordMap(new HashMap<>());
            }
            //查询文件收藏次数
            if (collectList!=null &&collectList.size()>0){
                long collectCount = collectList.stream()
                        .filter(a -> a.getFileId().equals(fileInformation.getFileId()))
                        .count();
                fileViewModel.setCollectCount(Math.toIntExact(collectCount));
            }
            //查询文件下载次数
            if (downloadRecordList!=null &&downloadRecordList.size()>0){
                long downloadRecordCount = downloadRecordList.stream()
                        .filter(a -> a.getFileId().equals(fileInformation.getFileId()))
                        .count();
                fileViewModel.setDownloadRecordCount(Math.toIntExact(downloadRecordCount));
            }
            //文件属于语言类型
            if(fileViewModel.getLanguageTypeId()!=null){
                LanguageType languageType = languageTypeMapper.selectById(fileViewModel.getLanguageTypeId());
                if(languageType!=null){
                    fileViewModel.setLanguageTypeName(languageType.getLanguageTypeName());
                }
            }else {
                fileViewModel.setLanguageTypeName("未知");
            }
            //判断是否点赞
            if(fileInformation.getUseridList()!=null&& fileInformation.getUseridList().contains(userId.toString())){
                fileViewModel.setIsLike(true);
            }else {
                fileViewModel.setIsLike(false);
            }
            //添加返回集合
            fileViewModelsList.add(fileViewModel);
        }
        // 使用Collections.sort()和自定义的Comparator根据NumberOfTimes字段排序
        Collections.sort(fileViewModelsList, (p1, p2) -> Integer.compare(p2.getNumberOfTimes(), p1.getNumberOfTimes()));
        newIPage.setRecords(fileViewModelsList);
        return Result.success("查询成功", newIPage);
    }

    /**
     * 点赞/或取消点赞
     * @param fileId
     * @param isIncrease
     * @param userId
     * @return
     */
    @Override
    public Result putlike(Integer fileId, boolean isIncrease, Integer userId) {
        System.out.println("----------------------------------213242342353245345-----------");
        System.out.println(isIncrease);
        if(userId==null){
            return Result.fail("为传递当前登陆人id");
        }
        FileInformation fileInformation = fileInformationMapper.selectById(fileId);
        if(fileInformation==null){
            return Result.fail("为查询到文件");
        }
        Integer numberOfTimes = fileInformation.getNumberOfTimes();
        if(numberOfTimes==null){
            numberOfTimes = 0;
        }
        if(isIncrease){
            //判断是否已经点过赞
            if(fileInformation.getUseridList()!=null){
                String[] parts = fileInformation.getUseridList().split(",");
                List<String> partList = new ArrayList<>(Arrays.asList(parts));
                if(partList.contains(userId.toString())){
                    return Result.fail("不能重复点赞");
                }
                partList.add(userId.toString());
                String s = String.join(",",partList);
                fileInformation.setUseridList(s);
            }else {
                fileInformation.setUseridList(userId.toString());
            }
            numberOfTimes++;
        }else {
            if(fileInformation.getUseridList()==null){
                return Result.fail("未有人点赞！");
            }
            String[] parts = fileInformation.getUseridList().split(",");
            List<String> partList = new ArrayList<>(Arrays.asList(parts));
            if(!partList.contains(userId.toString())){
                return Result.fail("你还未点赞！");
            }
            partList.remove(userId.toString());
            String s = String.join(",",partList);
            fileInformation.setUseridList(s);
            numberOfTimes--;
        }
        fileInformation.setNumberOfTimes(numberOfTimes);
        return fileInformationMapper.updateById(fileInformation)>0?Result.success("修改成功！"):Result.fail("修改失败！");
    }
}
